package com.yueya.basic.notice.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.basic.dept.model.Dept;
import com.yueya.basic.notice.model.Notice;
import com.yueya.basic.notice.model.NoticeDept;
import com.yueya.basic.notice.model.NoticeUser;
import com.yueya.common.model.Tree;
import com.yueya.common.util.DateUtil;
import com.yueya.common.util.UUIDGenerator;

/**
 * 
 * 
 * @author yangfeng
 * 
 */
public class NoticeService {

	@Before(Tx.class)
	public boolean save(Notice tzgg, String content, String scope,
			String depts, String users) {
		boolean bl = false;
		boolean bal = true;
		if (tzgg != null && tzgg.getStr("id") != null
				&& !"".equals(tzgg.getStr("id"))) {
			tzgg.set("content", content);
			tzgg.set("type", scope);
			tzgg.set("upddat", DateUtil.getDate(DateUtil.timeFormat));

			bl = tzgg.update();

			if (scope.equals("1")) {
				Db.update("delete from t_notice_dept where notice_id=? ",
						tzgg.getStr("id"));
				Db.update("delete from t_notice_user where notice_id=? ",
						tzgg.getStr("id"));

				if (depts != null && !"".equals(depts)) {
					bal = saveNoticeDept(depts, tzgg);
				}

				if (users != null && !"".equals(users)) {
					bal = saveNoticeUser(users, tzgg);
				}

			} else {
				Db.update("delete from t_notice_dept where notice_id=? ",
						tzgg.getStr("id"));
				Db.update("delete from t_notice_user where notice_id=? ",
						tzgg.getStr("id"));
			}

		} else {
			tzgg.set("id", UUIDGenerator.getUUID());
			tzgg.set("content", content);
			tzgg.set("type", scope);
			tzgg.set("status", "0");
			tzgg.set("delflag", "0");
			tzgg.set("credat", DateUtil.getDate(DateUtil.timeFormat));
			bl = tzgg.save();
			if (scope.equals("1")) {

				if (depts != null && !"".equals(depts)) {
					bal = saveNoticeDept(depts, tzgg);
				}

				if (users != null && !"".equals(users)) {
					bal = saveNoticeUser(users, tzgg);
				}

			}

		}

		return bl && bal;
	}

	private boolean saveNoticeDept(String depts, Notice tzgg) {
		boolean bal = false;
		String[] deptArrs = depts.split(",");
		for (int i = 0; i < deptArrs.length; i++) {
			NoticeDept record = new NoticeDept();
			record.set("id", UUIDGenerator.getUUID());
			record.set("notice_id", tzgg.getStr("id"));
			record.set("dept_id", deptArrs[i]);
			bal = record.save();
			if (bal == false) {
				try {
					DbKit.getConfig().getConnection().rollback();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return bal;
	}

	private boolean saveNoticeUser(String users, Notice tzgg) {
		boolean bal = false;
		String[] userArrs = users.split(",");
		for (int i = 0; i < userArrs.length; i++) {
			NoticeUser record = new NoticeUser();
			record.set("id", UUIDGenerator.getUUID());
			record.set("notice_id", tzgg.getStr("id"));
			record.set("user_id", userArrs[i]);
			bal = record.save();
			if (bal == false) {
				try {
					DbKit.getConfig().getConnection().rollback();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return bal;
	}

	public Page<Record> pagination(int pageNumber, int pageSize,
			Map<String, Object> map) {

		String select = "select a.*,b.user_name username,c.dept_name deptname ";
		StringBuffer sb = new StringBuffer(
				" from t_notice  a left join t_user b on a.userid=b.user_id left join t_dept c on a.deptid=c.dept_id where 1=1 ");
		if (map.get("delflag") != null && !"".equals(map.get("delflag"))) {
			sb.append(" and a.delflag = '" + map.get("delflag") + "' ");
		}

		if (map.get("flag") != null && "1".equals(map.get("flag"))) {
			sb.append(" and a.userid = '" + map.get("userid") + "' ");
		}

		if (map.get("name") != null && !"".equals(map.get("name"))) {
			sb.append(" and ( a.title like '%" + map.get("name") + "%'  )");
		}
		if (map.get("status") != null && !"".equals(map.get("status"))) {
			sb.append(" and  a.status = '" + map.get("status") + "'  ");
		}

		sb.append("  order by a.credat desc ");

		String sql = sb.toString();
		System.out.println(sql);
		Page<Record> page = Db.paginate(pageNumber, pageSize, select, sql);

		return page;

	}

	@SuppressWarnings("rawtypes")
	public Page pagination(int pageNumber, int pageSize, Map map,
			boolean withReadStatus) {
		Page page = null;
		String select = "";
		StringBuffer sb = new StringBuffer();
		if (withReadStatus) {
			if (map.get("userid").equals("0001")) {
				select = "select a.*,b.user_name username,c.dept_name deptname,"
						+ "(select count(s.id) as count from t_notice_status s where s.user_id = '"
						+ map.get("userid")
						+ "' and s.notice_id = a.id ) as readstatus";
				sb.append(" from t_notice  a left join t_user b on a.userid=b.user_id left join t_dept c on a.deptid=c.dept_id where a.delflag='0' ");
				if (map.get("name") != null && !"".equals(map.get("name"))) {
					sb.append(" and ( a.title like '%" + map.get("name")
							+ "%'  )");
				}
				if (map.get("status") != null && !"".equals(map.get("status"))) {
					sb.append(" and  a.status = '" + map.get("status") + "'  ");
				}
				sb.append("  order by a.credat desc ");
			} else {

				select = "select * ";
				sb.append(" from ( select b.id id,b.title title,b.credat credat,b.pubdat pubdat,c.user_name username,d.dept_name deptname,(select count(s.id) as count from t_notice_status s where s.user_id='"
						+ map.get("userid")
						+ "' and s.notice_id = b.id) as readstatus  ");
				sb.append(" from  t_notice b left join t_user c on b.userid=c.user_id left join t_dept d on b.deptid=d.dept_id ");
				sb.append(" where b.delflag='0' and b.type='0' and b.status='"
						+ map.get("status") + "' and b.title like '%"
						+ map.get("name") + "%'   ");
				sb.append(" union  ");
				sb.append(" select b.id id,b.title title,b.credat credat,b.pubdat pubdat,c.user_name username,d.dept_name deptname,(select count(s.id) as count from t_notice_status s where s.user_id='"
						+ map.get("userid")
						+ "' and s.notice_id = b.id) as readstatus  ");
				sb.append(" from  t_notice_user a left join t_notice b on a.notice_id=b.id left join t_user c on b.userid=c.user_id left join t_dept d on b.deptid=d.dept_id  ");
				sb.append(" where a.user_id='" + map.get("userid")
						+ "' and b.status='" + map.get("status")
						+ "' and  b.delflag='0'  and b.title like '%"
						+ map.get("name") + "%'  ");
				sb.append(" union  ");
				sb.append(" select b.id id,b.title title,b.credat credat,b.pubdat pubdat,c.user_name username,d.dept_name deptname,(select count(s.id) as count from t_notice_status s where s.user_id='"
						+ map.get("userid")
						+ "' and s.notice_id = b.id) as readstatus  ");
				sb.append(" from  t_notice_dept a left join t_notice b on a.notice_id=b.id left join t_user c on b.userid=c.user_id left join t_dept d on b.deptid=d.dept_id  ");
				sb.append(" where a.dept_id = (select du.dept_id from t_dept_user du where du.user_id='"
						+ map.get("userid")
						+ "') and b.status='"
						+ map.get("status")
						+ "' and  b.delflag='0' and b.title like '%"
						+ map.get("name") + "%'  ) tm order by tm.pubdat desc, tm.credat desc ");
			}

			String sql = sb.toString();
			System.out.println(sql);
			page = Db.paginate(pageNumber, pageSize, select, sql);
		}
		return page;
	}

	public Record getNoticeById(String id) {
		Record r = Db
				.findFirst(
						"select a.*,b.user_name usernam,c.dept_name deptnam from t_notice  a left join t_user b on a.userid=b.user_id left join t_dept c on a.deptid=c.dept_id where  a.id=?  order by a.credat desc",
						id);

		return r;
	}

	/**
	 * 获取部门树，关联通知
	 * 
	 * @param id
	 * @return
	 */
	public List<Tree> getTreeNoticeDept(String id) {
		List<Record> list = Db.find(
				"SELECT * FROM t_notice_dept WHERE notice_id=?", id);
		Record r = null;
		List<String> deptlist = new ArrayList<String>();
		String deptid = "";
		for (int i = 0; i < list.size(); i++) {
			r = list.get(i);
			deptid = r.getStr("dept_id");
			deptlist.add(deptid);
		}
		Tree t = Dept.service.recursiveTree("000", deptlist);
		List<Tree> ret = new ArrayList<Tree>();
		ret.add(t);
		return ret;
	}

	/**
	 * 获取部门用户树，关联通知
	 * 
	 * @param id
	 * @return
	 */
	public List<Tree> getTreeNoticeUser(String id) {
		List<Record> list = Db.find(
				"SELECT * FROM t_notice_user WHERE notice_id=?", id);
		List<Tree> rt = Dept.dao.toTreeList(Dept.dao._r(), "", "");
		List<Tree> rl = Dept.dao.toTreeList2(Dept.dao._rtl());
		List<Tree> ret = Dept.dao.splitTreeU(rt, rl, rl, list);
		parseUserTree(ret, list);
		return ret;
	}

	private void parseUserTree(List<Tree> list, List<Record> checkedList) {
		for (Tree temp : list) {
			for (Record t : checkedList) {
				if (t.get("user_id").equals(temp.getId()))
					temp.setChecked(true);
			}
			if (temp.getChildren() != null)
				parseUserTree(temp.getChildren(), checkedList);
		}
	}

}
